<template>
  <el-dialog
    top="30px"
    width="1000px"
    append-to-body
    :title="dialogTitle"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :before-close="beforeClose"
  >
    <h4 class="archive-title">客户信息</h4>
    <table v-if="isCompany" class="table table-bordered table-sm">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td class="bg-light">企业名称</td>
          <td>{{ formData.customer_name }}</td>
          <td class="bg-light">经营地址</td>
          <td>{{ formData.address || '' }}</td>
        </tr>
        <tr>
          <td class="bg-light">组织类型</td>
          <td>{{ orgClassName }}</td>
          <td class="bg-light">统一社会信用代码</td>
          <td>{{ formData.register_no || '' }}</td>
        </tr>
        <tr>
          <td class="bg-light">负责人</td>
          <td>{{ formData.corp_name || '' }}</td>
          <td class="bg-light">负责人身份证号</td>
          <td>{{ formData.lender_idcard || '' }}</td>
        </tr>
        <tr>
          <td class="bg-light">联系电话</td>
          <td>{{ formData.mobile_no || '' }}</td>
          <td class="bg-light">家庭住址</td>
          <td>{{ farmAddress }}</td>
        </tr>
      </tbody>
    </table>
    <table v-else class="table table-bordered table-sm">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td class="bg-light">企业名称</td>
          <td>{{ formData.customer_name }}</td>
          <td class="bg-light">家庭住址</td>
          <td>{{ farmAddress }}</td>
        </tr>
        <tr>
          <td class="bg-light">联系电话</td>
          <td>{{ formData.mobile_no || '' }}</td>
          <td class="bg-light">负责人身份证号</td>
          <td>{{ formData.lender_idcard || '' }}</td>
        </tr>
      </tbody>
    </table>

    <h4 class="archive-title">项目信息</h4>
    <table class="table table-bordered table-sm">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td class="bg-light">担保额度（万元）</td>
          <td>{{ formData.reply_funds }}</td>
          <td class="bg-light">用款期限（年）</td>
          <td>{{ formData.load_years || '' }}</td>
        </tr>
        <tr>
          <td class="bg-light">放款机构</td>
          <td>{{ formData.bank_name || '' }}</td>
          <td class="bg-light">放款利率（%）</td>
          <td>{{ formData.load_rate || '' }}</td>
        </tr>
        <tr>
          <td class="bg-light">担保费率（%）</td>
          <td>{{ formData.gua_rate || '' }}</td>
          <td class="bg-light">担保期间</td>
          <td>{{ loadPeriod }}</td>
        </tr>
        <tr>
          <td class="bg-light">项目主办人</td>
          <td>{{ formData.res_a_name || '' }}</td>
          <td class="bg-light">项目协办人</td>
          <td>{{ formData.res_b_name || '' }}</td>
        </tr>
        <tr>
          <td class="bg-light">项目类型</td>
          <td>{{ guaTypeLabel }}</td>
          <td class="bg-light">银行分险比例（%）</td>
          <td>{{ formData.bank_risk_rate }}</td>
        </tr>
        <tr v-if="guaType !== 2">
          <td class="bg-light">联保机构</td>
          <td>{{ formData.recommend_service_name || '' }}</td>
          <td class="bg-light">联保比例（%）</td>
          <td>{{ formData.join_risk_rate || '-' }}</td>
        </tr>
        <tr>
          <td class="bg-light">项目电子附件</td>
          <td colspan="3" class="position-relative">
            <div
              v-loading="relatedLoading"
              element-loading-spinner="el-icon-loading"
              element-loading-custom-class="archive-td-loading"
            >
              <el-button type="text" class="py-0" @click="handleAttachView('file')">
                放款登记
              </el-button>
              <el-button type="text" class="py-0" @click="handleAttachView('register')">
                签约登记
              </el-button>
              <el-tooltip
                effect="light"
                content="暂无担保意向函"
                placement="bottom"
                :disabled="hasEleLetter"
              >
                <!-- button外添加一个div是为了防止button disabled后，tooltip无效 -->
                <div class="d-inline-block">
                  <el-button
                    type="text"
                    class="py-0"
                    :class="hasEleLetter ? '' : 'text-muted'"
                    :disabled="!hasEleLetter"
                    @click="handleAttachView('letter')"
                  >
                    担保意向函
                  </el-button>
                </div>
              </el-tooltip>
              <el-button type="text" class="py-0" @click="handleAttachView('approval')">
                合同审批表
              </el-button>
              <el-button type="text" class="py-0" @click="handleAttachView('contract')">
                合同附件
              </el-button>
              <el-button type="text" class="py-0" @click="handleAttachView('attach')">
                项目附件
              </el-button>
              <el-button type="text" class="py-0" @click="handleAttachView('postloan')">
                贷后附件
              </el-button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>

    <h4 class="archive-title">归档信息</h4>
    <table v-if="isEdit" class="table table-bordered table-sm">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td class="bg-light">档案编号</td>
          <td class="input-td">
            <input class="form-control" placeholder="档案编号" v-model="form.archives_no" />
          </td>
          <td class="bg-light">归档时间</td>
          <td class="input-td">
            <el-date-picker
              class="w-100"
              v-model="form.archives_time"
              type="date"
              :clearable="false"
              placeholder="归档时间"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </td>
        </tr>
        <tr>
          <td class="bg-light">档案柜号</td>
          <td class="input-td">
            <input class="form-control" placeholder="档案柜号" v-model="form.cabinet_no" />
          </td>
          <td class="bg-light">操作人员</td>
          <td>{{ operatePerson }}</td>
        </tr>
        <tr>
          <td class="bg-light">档案备注</td>
          <td colspan="3" class="input-td">
            <el-input v-model="form.remark" type="textarea" placeholder="档案备注"></el-input>
          </td>
        </tr>
      </tbody>
    </table>
    <table v-else class="table table-bordered table-sm">
      <colgroup>
        <col width="20%" />
        <col width="30%" />
        <col width="20%" />
        <col width="30%" />
      </colgroup>
      <tbody>
        <tr>
          <td class="bg-light">档案编号</td>
          <td>{{ form.archives_no }}</td>
          <td class="bg-light">归档时间</td>
          <td>{{ form.archives_time }}</td>
        </tr>
        <tr>
          <td class="bg-light">档案柜号</td>
          <td>{{ form.cabinet_no }}</td>
          <td class="bg-light">操作人员</td>
          <td>{{ operatePerson }}</td>
        </tr>
        <tr>
          <td class="bg-light">档案备注</td>
          <td colspan="3">{{ form.remark }}</td>
        </tr>
      </tbody>
    </table>

    <archive-attach
      ref="attachRef"
      v-bind="$attrs"
      v-on="$listeners"
      :visible="visible"
      :form-data="formData"
      :view-mode="!isEdit"
    ></archive-attach>

    <div class="text-center" v-if="isEdit">
      <el-button type="warning" class="btn-long" :loading="loading" @click="handleSave(1)">
        {{ eidtBtnLabel }}
      </el-button>
      <el-button
        type="primary"
        class="btn-long"
        v-if="archiveStatus <= 1"
        :loading="loading"
        @click="handleSave(2)"
      >
        完成归档
      </el-button>
      <el-button class="btn-long" :disabled="loading" @click="beforeClose">取消</el-button>
    </div>

    <postloan-file
      :visible.sync="attachVisible"
      :related-data="relatedData"
      :tab-name="tabName"
    ></postloan-file>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'
import { dateFormat } from '@vimi/utils-tool'
// import { deleteOss } from '@/common/api/oss'
import { enumGuaTypeAbbr, enumArchivesStatus } from '@/credit/views/city/archives/mixins'
import { personalOrgClass } from '@/credit/views/city/customer/blackList/mixins'
import { addHistory } from '@/credit/views/city/archives/historyMixins'
import { enumCompanyType } from '@/gov/plugins/enum'

import ArchiveAttach from '@/credit/views/city/archives/ArchiveAttach'
import PostloanFile from '@/credit/views/city/self/components/PostloanFile'

export default {
  components: {
    ArchiveAttach,
    PostloanFile,
  },
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
    viewMode: {
      type: Boolean,
      default: true,
    },
    title: String,
  },
  data() {
    return {
      attachVisible: false,
      tabName: 'file',
      loading: false,
      form: {
        archives_no: '',
        archives_time: '',
        cabinet_no: '',
        remark: '',
      },
      deleteFiles: [],
      addFiles: [],

      relatedLoading: false,
      relatedData: {},
    }
  },
  computed: {
    ...mapGetters(['user', 'userId']),
    archiveId() {
      return this.formData.project_archives_id
    },
    farmAddress() {
      const { formData } = this
      return formData.family_address || formData.family_address_code_detail || ''
    },
    loadPeriod() {
      const { formData } = this
      return (formData.load_date || '- ') + ' 至 ' + (formData.load_end_date || ' -')
    },
    guaType() {
      return +this.formData.gua_type
    },
    guaTypeLabel() {
      return enumGuaTypeAbbr[this.guaType] || ''
    },
    isCompany() {
      return !personalOrgClass.includes(this.formData.org_class)
    },
    isEdit() {
      return !this.viewMode
    },
    archiveStatus() {
      return this.formData.archives_status
    },
    eidtBtnLabel() {
      return this.archiveStatus === 2 ? '完成修改' : '保存数据'
    },
    operatePerson() {
      return this.formData.submit_person_name || this.user.realName || ''
    },
    orgClassName() {
      return enumCompanyType[this.formData.org_class] || '-'
    },
    dialogTitle() {
      return this.title || `归档登记（${enumArchivesStatus[this.archiveStatus] || '-'}）`
    },

    // 有无担保意见函，与弹窗保持一致
    hasEleLetter() {
      return +(this.relatedData.ele_letter_status || 0) > 0
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.init()
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },

    init() {
      Object.keys(this.form).forEach(key => {
        this.form[key] = this.formData[key] || ''
      })
      if (!this.form.archives_time) {
        this.form.archives_time = dateFormat(new Date(), 'yyyy-MM-dd')
      }
      this.getRelatedData()
    },

    getRelatedData() {
      const relatedId = this.formData.customer_related_id
      this.relatedLoading = true
      this.$api
        .getData(this.$serviceName, 'customer_related', { 'customer_related_id.eq': relatedId })
        .then(res => {
          const data = (res && res.data && res.data[0]) || {}
          this.relatedData = data
        })
        .catch(err => {
          this.relatedData = {
            ...this.formData,
            ele_letter_status: 2,
          }
          throw new Error(err)
        })
        .finally(() => {
          this.relatedLoading = false
        })
    },

    handleAttachView(tab) {
      this.tabName = tab
      this.attachVisible = true
    },

    handleSave(status) {
      const msg = this.validate()
      if (msg) {
        return this.$message.error(msg)
      }

      this.loading = true
      this.$refs.attachRef
        .submit()
        .then(({ files, deleteFiles, addFiles }) => {
          this.deleteFiles = deleteFiles
          this.addFiles = addFiles
          return this.save(files, status)
        })
        .finally(() => {
          this.loading = false
        })
    },

    save(attach, status = 1) {
      const { archiveId, archiveStatus } = this
      const slaveData = attach
      const masterData = {
        ...this.form,
        archives_status: archiveStatus > 1 ? archiveStatus : status,
        attachment_count: attach.length,
        submit_person_name: this.user.realName,
      }

      if (archiveId) {
        masterData.project_archives_id = archiveId
        slaveData.forEach(it => {
          it.project_archives_id = archiveId
        })
      } else {
        masterData.customer_related_id = this.formData.customer_related_id
      }

      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: 'project_archives',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'project_archives_detail',
      }

      const api = archiveId
        ? this.$api.relatedUpdate(this.$serviceName, formData)
        : this.$api.relatedBatch(this.$serviceName, formData)
      return api
        .then(res => {
          this.$message.success('操作成功！')
          this.$emit('success', res)
          this.deleteOss()

          if (archiveId) {
            this.addHistoryRecord(archiveId)
          }

          this.beforeClose()
        })
        .catch(err => {
          this.$message.error('操作失败，请重试！')
          throw new Error(err)
        })
    },

    // 验证
    validate() {
      const rules = {
        archives_no: '请填写档案编号',
        cabinet_no: '请填写档案柜号',
      }
      const keys = Object.keys(rules)
      for (const key of keys) {
        if (!this.form[key]) {
          return rules[key]
        }
      }
    },

    // 删除OSS
    deleteOss() {
      // deleteOss(this.deleteFiles)
    },

    // 添加操作记录
    addHistoryRecord(archiveId) {
      const getRecordItem = (key, label, newVal, oldVal, type) => ({
        update_record_field: key,
        update_record_field_name: label,
        update_record_id: archiveId,
        update_record_value_aft: newVal,
        update_record_value_bef: oldVal,
        update_type: type,
      })

      const masterData = {
        record_id: archiveId,
        submit_person: this.userId,
        submit_person_name: this.user.realName,
      }

      // 改变的数据
      const slaveData = []
      const config = [
        { key: 'archives_no', label: '档案编号' },
        { key: 'archives_time', label: '归档时间' },
        { key: 'cabinet_no', label: '档案柜号' },
        { key: 'remark', label: '档案备注' },
      ]
      for (const cfg of config) {
        const { key, label } = cfg
        const oldVal = this.formData[key]
        const newVal = this.form[key]
        if (newVal !== oldVal) {
          slaveData.push(getRecordItem(key, label, newVal, oldVal, 1))
        }
      }
      // 附件新增
      for (const fileUrl of this.addFiles) {
        slaveData.push(getRecordItem('attachment', '附件', fileUrl, '', 2))
      }
      // 附件删除
      for (const fileUrl of this.deleteFiles) {
        slaveData.push(getRecordItem('attachment', '附件', fileUrl, '', 3))
      }

      return addHistory(masterData, slaveData)
    },
  },
}
</script>

<style lang="scss" scoped>
.archive-title {
  font-size: 1.1rem;
  font-weight: bold;
}
/deep/ .archive-td-loading .el-loading-spinner {
  margin-top: -10px;
}
</style>
